package com.tmall.wireless.virtualviewdemo.utils.imageloader.core.decode;

import com.tmall.wireless.virtualviewdemo.utils.imageloader.core.assist.ImageScaleType;
import com.tmall.wireless.virtualviewdemo.utils.imageloader.core.assist.ImageSize;
import com.tmall.wireless.virtualviewdemo.utils.imageloader.core.download.ImageDownloader;
import com.tmall.wireless.virtualviewdemo.utils.imageloader.utils.ImageSizeUtils;
import com.tmall.wireless.virtualviewdemo.utils.imageloader.utils.IoUtils;
import com.tmall.wireless.virtualviewdemo.utils.imageloader.utils.L;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.ImageInfo;
import ohos.media.image.common.Size;

import java.io.IOException;
import java.io.InputStream;

public class BaseImageDecoder implements ImageDecoder {

    protected static final String LOG_SUBSAMPLE_IMAGE = "Subsample original image (%1$s) to %2$s (scale = %3$d) [%4$s]";
    protected static final String LOG_SCALE_IMAGE = "Scale subsampled image (%1$s) to %2$s (scale = %3$.5f) [%4$s]";
    protected static final String LOG_ROTATE_IMAGE = "Rotate image on %1$d\u00B0 [%2$s]";
    protected static final String LOG_FLIP_IMAGE = "Flip image horizontally [%s]";
    protected static final String ERROR_NO_IMAGE_STREAM = "No stream for image [%s]";
    protected static final String ERROR_CANT_DECODE_IMAGE = "Image can't be decoded [%s]";

    protected final boolean loggingEnabled;


    public BaseImageDecoder(boolean loggingEnabled) {
        this.loggingEnabled = loggingEnabled;
    }

    /**
     * during decoding (depend on incoming parameters).
     *
     * @param decodingInfo Needed data for decoding image
     * @return Decoded bitmap
     * @throws IOException                   if some I/O exception occurs during image reading
     * @throws UnsupportedOperationException if image URI has unsupported scheme(protocol)
     */
    @Override
    public PixelMap decode(ImageDecodingInfo decodingInfo) throws IOException {
        PixelMap decodedBitmap = null;
        ImageFileInfo imageFileInfo;
        ImageSize imageSize = null;
        InputStream imageStream = getImageStream(decodingInfo);
        if (imageStream == null) {
            L.e(ERROR_NO_IMAGE_STREAM, decodingInfo.getImageKey());
            return null;
        }
        try {
//            imageFileInfo = defineImageSizeAndRotation(imageStream, decodingInfo);
//            imageStream = resetStream(imageStream, decodingInfo);
//            ImageSource.DecodingOptions decodingOptions = prepareDecodingOptions(imageFileInfo.imageSize, decodingInfo);
//            ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
//            decodedBitmap = ImageSource.create(imageStream, sourceOptions)
//                    .createPixelmap(decodingOptions);

            ImageSource imageSource = ImageSource.create(imageStream, new ImageSource.SourceOptions());
            ImageInfo imageInfo = imageSource.getImageInfo();
            Size size = imageInfo.size;
            ExifInfo exif;
            String imageUri = decodingInfo.getImageUri();
            String encodedFormat = imageSource.getSourceInfo().encodedFormat;
            if (decodingInfo.shouldConsiderExifParams() && canDefineExifParams(imageUri, encodedFormat)) {
                exif = defineExifOrientation(imageUri);
            } else {
                exif = new ExifInfo();
            }
            imageSize = new ImageSize(size.width, size.height, exif.rotation);
            imageFileInfo = new ImageFileInfo(imageSize, exif);
            ImageSource.DecodingOptions decodingOptions = prepareDecodingOptions(imageFileInfo, decodingInfo);
            decodedBitmap = imageSource.createPixelmap(decodingOptions);

        } finally {
            IoUtils.closeSilently(imageStream);
        }
        if (decodedBitmap == null) {
            L.e(ERROR_CANT_DECODE_IMAGE, decodingInfo.getImageKey());
        }
        return decodedBitmap;
    }

    protected InputStream getImageStream(ImageDecodingInfo decodingInfo) throws IOException {
        return decodingInfo.getDownloader().getStream(decodingInfo.getImageUri(), decodingInfo.getExtraForDownloader());
    }

    protected ImageFileInfo defineImageSizeAndRotation(InputStream imageStream, ImageDecodingInfo decodingInfo) {

        ImageSource imageSource = ImageSource.create(imageStream, new ImageSource.SourceOptions());
        ImageInfo imageInfo = imageSource.getImageInfo();
        Size size = imageInfo.size;
        ExifInfo exif;
        String imageUri = decodingInfo.getImageUri();
        String encodedFormat = imageSource.getSourceInfo().encodedFormat;
        if (decodingInfo.shouldConsiderExifParams() && canDefineExifParams(imageUri, encodedFormat)) {
            exif = defineExifOrientation(imageUri);
        } else {
            exif = new ExifInfo();
        }
        return new ImageFileInfo(new ImageSize(size.width, size.height, exif.rotation), exif);
    }

    private boolean canDefineExifParams(String imageUri, String mimeType) {
        return "image/jpeg".equalsIgnoreCase(mimeType) && (ImageDownloader.Scheme.ofUri(imageUri) == ImageDownloader.Scheme.FILE);
    }

    protected ExifInfo defineExifOrientation(String imageUri) {
        int rotation = 0;
        boolean flip = false;
//        try {
//            ExifInterface exif = new ExifInterface(ImageDownloader.Scheme.FILE.crop(imageUri));
//            int exifOrientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
//            switch (exifOrientation) {
//                case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
//                    flip = true;
//                case ExifInterface.ORIENTATION_NORMAL:
//                    rotation = 0;
//                    break;
//                case ExifInterface.ORIENTATION_TRANSVERSE:
//                    flip = true;
//                case ExifInterface.ORIENTATION_ROTATE_90:
//                    rotation = 90;
//                    break;
//                case ExifInterface.ORIENTATION_FLIP_VERTICAL:
//                    flip = true;
//                case ExifInterface.ORIENTATION_ROTATE_180:
//                    rotation = 180;
//                    break;
//                case ExifInterface.ORIENTATION_TRANSPOSE:
//                    flip = true;
//                case ExifInterface.ORIENTATION_ROTATE_270:
//                    rotation = 270;
//                    break;
//            }
//        } catch (IOException e) {
//            L.w("Can't read EXIF tags from file [%s]", imageUri);
//        }
        return new ExifInfo(rotation, flip);
    }

    protected ImageSource.DecodingOptions prepareDecodingOptions(ImageFileInfo imageFileInfo, ImageDecodingInfo
            decodingInfo) {
        ImageSize imageSize = imageFileInfo.imageSize;
        ExifInfo exif = imageFileInfo.exif;
        int rotation = exif.rotation;

        ImageScaleType scaleType = decodingInfo.getImageScaleType();
        int scale;
        if (scaleType == ImageScaleType.NONE) {
            scale = 1;
        } else if (scaleType == ImageScaleType.NONE_SAFE) {
            scale = ImageSizeUtils.computeMinImageSampleSize(imageSize);
        } else {
            ImageSize targetSize = decodingInfo.getTargetSize();
            boolean powerOf2 = scaleType == ImageScaleType.IN_SAMPLE_POWER_OF_2;
            scale = ImageSizeUtils.computeImageSampleSize(imageSize, targetSize, decodingInfo.getViewScaleType(), powerOf2);
        }
        if (scale > 1 && loggingEnabled) {
            L.d(LOG_SUBSAMPLE_IMAGE, imageSize, imageSize.scaleDown(scale), scale, decodingInfo.getImageKey());
        }

        ImageSource.DecodingOptions decodingOptions = decodingInfo.getDecodingOptions();
        decodingOptions.sampleSize = scale;
        decodingOptions.rotateDegrees = rotation;


        return decodingOptions;
    }

    protected InputStream resetStream(InputStream imageStream, ImageDecodingInfo decodingInfo) throws IOException {
        if (imageStream.markSupported()) {
            try {
                imageStream.reset();
                return imageStream;
            } catch (IOException ignored) {
            }
        }
        IoUtils.closeSilently(imageStream);
        return getImageStream(decodingInfo);
    }


    protected static class ExifInfo {

        public final int rotation;
        public final boolean flipHorizontal;

        protected ExifInfo() {
            this.rotation = 0;
            this.flipHorizontal = false;
        }

        protected ExifInfo(int rotation, boolean flipHorizontal) {
            this.rotation = rotation;
            this.flipHorizontal = flipHorizontal;
        }
    }

    protected static class ImageFileInfo {

        public final ImageSize imageSize;
        public final ExifInfo exif;

        protected ImageFileInfo(ImageSize imageSize, ExifInfo exif) {
            this.imageSize = imageSize;
            this.exif = exif;
        }
    }
}